package com.sdd.rpi_mobile.resourceLists;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.sdd.rpi_mobile.R;
import com.sdd.rpi_mobile.homeScreen.GridChooser;

/** Displays and controls lists which are generated from resource files. */
public class ListActivity extends Activity {
	@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_list_view_loader);
		
		//Initialize the UI components
		ListView listView = (ListView) findViewById(R.id.list_view);
		
		//Enable the Home button in the action bar.
		if (Build.VERSION.SDK_INT >= 14) {
			getActionBar().setHomeButtonEnabled(true);
		}
		
		//Get variable from another activity
		Bundle bundle = this.getIntent().getExtras();
		final int resID = bundle.getInt("resource");
	
		final ListViewLoader listviewloader = ListFactory.newList(this, resID);
		ArrayAdapter<String> arrayadapter = listviewloader.getArrayAdapter(resID);
		listView.setAdapter(arrayadapter);

		//Setup on click listener
		 listView.setOnItemClickListener(new OnItemClickListener() {                               
			 public void onItemClick(AdapterView<?> listAdapter, View myView, int indexClicked,long arg3) {
				 Intent intent = listviewloader.getIntent(myView.getContext(), resID, indexClicked);
				 startActivity(intent);
			 }
         });
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		//Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.list, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	        case android.R.id.home:
	            //App icon in action bar clicked; go home
	            Intent intent = new Intent(this, GridChooser.class);
	            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	            startActivity(intent);
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
}
